<?php
include ("functions.php");

if ($_GET["name"] == "") { $jmeno = $lang['route'];}
	else {$jmeno = urldecode($_GET["name"]);}
$adresa = "http://maps.google.com/maps?saddr=".$_GET["from"]."&daddr=".$_GET["to"]."&oe=utf8&output=kml&hl=".$lang['lang'];
$retezec = file_get_contents($adresa);

if (strpos($retezec, "<Document><name>")) {
	
	header("Content-Description: File Transfer");
	header("Content-Type: application/force-download; charset=\"UTF-8\"");
	header("Content-Disposition: attachment; filename=\"route.kml\"");
	
	$sxml = new simplexml;
	$data = $sxml->xml_load_file($adresa);
	$kml = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.0"><Document><name>'.diakritika($lang['calculated'].$jmeno).'</name><Style id="locify"><IconStyle><Icon><href>'.SERVICE_URL.'crossroad.png</href></Icon></IconStyle></Style><Folder>';
	foreach($data->Document->Placemark as $placemark) {
		if (!($placemark->Point->coordinates == "")) {
			$kml .= '<Placemark><name>'.diakritika($lang['crossroad']).'</name><description>'.diakritika($placemark->name).'</description><styleUrl>#locify</styleUrl><Point><coordinates>'.$placemark->Point->coordinates.'</coordinates></Point></Placemark>';
			if ($_GET["full"] == 0) $souradnice .= $placemark->Point->coordinates." ";
		} else {
			$kml .= '</Folder><Placemark><name><![CDATA['.route_info($placemark->description).']]></name><GeometryCollection><LineString><coordinates>';
			if ($_GET["full"] == 0) { $kml .= $souradnice; }
			else {
			   if (strpos($retezec, "</coordinates></LineString><LineString><coordinates>")) {
				foreach($placemark->GeometryCollection->LineString as $neco) {
					$kml .= $neco->coordinates;
				}
			   } else {
			   	$kml .= $placemark->GeometryCollection->LineString->coordinates;
			   }
			}
			$kml .= '</coordinates></LineString></GeometryCollection></Placemark>';
		}	
	}
	$kml .= '</Document></kml>';
	print $kml;
} else {
	echo '<?xml version="1.0" encoding="utf-8" ?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" xmlns:locify="http://client.locify.com/locify_ns/1.0" xml:lang="'.$lang["lang"].'" lang="'.$lang["lang"].'">
	<head>
		<title>'.$jmeno.'</title>
	</head>
	<body>
		<div>'
			.$lang["route"].' '.$jmeno.' '.$lang["not_found"].'
		</div>
	</body>
	</html>';
}		
?>
